package cn.yl.comment.server.controller;


import cn.yl.api.server.result.Result;
import cn.yl.comment.server.entity.CourseComment;
import cn.yl.comment.server.entity.dto.CourseCommentDto;
import cn.yl.comment.server.entity.vo.CourseCommentVo;
import cn.yl.comment.server.service.CourseCommentService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 课程留言表 前端控制器
 * </p>
 *
 * @author yl
 * @since 2022-04-22
 */
@RestController
@RequestMapping("/course/comment")
public class CourseCommentController {
    private final CourseCommentService courseCommentService;


    public CourseCommentController(CourseCommentService courseCommentService) {
        this.courseCommentService = courseCommentService;
    }

    @GetMapping("getCourseCommentList/{courseId}/{current}/{size}")
    public Result getCourseCommentList(@PathVariable Integer courseId, @PathVariable Integer current, @PathVariable Integer size) {
        List<CourseCommentDto> list = courseCommentService.getCourseCommentList(courseId, current, size);
        return Result.ok().setData("items", list);
    }

    @PutMapping("saveCourseComment")
    public Result saveCourseComment(@RequestBody CourseCommentVo courseCommentVo, HttpServletRequest request) {
        if(courseCommentVo.getComment()!=null){
            String jwt = request.getHeader("jwt");
            return this.courseCommentService.saveCourseComment(courseCommentVo, jwt) ? Result.ok() : Result.error();
        }else {
            return Result.error().setMessage("不能为空");
        }
    }

    @PutMapping("saveFavorite/{commentId}")
    public Result saveFavorite(HttpServletRequest request, @PathVariable Integer commentId) {
        String jwt = request.getHeader("jwt");
        return this.courseCommentService.saveFavorite(commentId, jwt) ? Result.ok() : Result.error();
    }

    @PutMapping("cancelFavorite/{commentId}")
    public Result cancelFavorite(HttpServletRequest request, @PathVariable Integer commentId) {
        String jwt = request.getHeader("jwt");
        return this.courseCommentService.cancelFavorite(commentId, jwt) ? Result.ok() : Result.error();
    }

    @PutMapping("updateByUserName")
    public void updateByUserName(Integer userId,String userName){
        UpdateWrapper<CourseComment> wrapper = new UpdateWrapper<>();
        wrapper.eq("user_id",userId).set("user_name",userName);
        this.courseCommentService.update(wrapper);
    }

}

